package com.chukun.concurrency.atomic;

import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;

/**
 * AtomicIntegerFieldUpdater使用需要注意：
 * 类里面必须要有一个用volatile的field
 * 初始化的时候，需要使用这个被volatile的field
 */

@Slf4j
public class AtomicFieldUpdaterOperator {

    static  AtomicIntegerFieldUpdater<AtomicFieldUpdaterOperator> atomicIntegerFieldUpdater = AtomicIntegerFieldUpdater.newUpdater(AtomicFieldUpdaterOperator.class,"count");

    @Getter
    private  volatile  int count=100;

    public static void main(String[] args) {
      AtomicFieldUpdaterOperator atomicFieldUpdaterOperator = new AtomicFieldUpdaterOperator();
      if(atomicIntegerFieldUpdater.compareAndSet(atomicFieldUpdaterOperator,100,120)){
           log.info("the old value :{}",100);
      }
      if (atomicIntegerFieldUpdater.compareAndSet(atomicFieldUpdaterOperator, 100, 120)) {
            log.info("update success 2, {}", atomicFieldUpdaterOperator.getCount());
        } else {
            log.info("update failed, {}", atomicFieldUpdaterOperator.getCount());
        }
    }
}
